package pool;

import java.util.concurrent.*;

/**
 * @author lyx
 * @Date 2021/6/26 10:24
 * 四大拒绝策略
 *  new ThreadPoolExecutor.AbortPolicy() //当max和队列满了,还进来线程,则拒绝,抛出异常
 *  new ThreadPoolExecutor.CallerRunsPolicy()  //当max和队列满了,哪来回哪去
 *  new ThreadPoolExecutor.DiscardOldestPolicy() //当max和队列满了,尝试与最早的线程竞争
 *  new ThreadPoolExecutor.DiscardPolicy() // 当max和队列满了,丢掉任务,不抛出异常
 */
public class HankMakePool {

    public static void main(String[] args) {

        //手动创建池, 重点:七大参数
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,//核心线程数
                5,//最大核心线程
                10,//超时10s
                TimeUnit.SECONDS,//单位秒
                new LinkedBlockingQueue<>(4),//阻塞队列大小4,若满,则触发Max
                Executors.defaultThreadFactory(),//默认线程工厂
                new ThreadPoolExecutor.CallerRunsPolicy()//四大策略 见上注解
        );

        try {
            //最多能执行 5+4 个线程
            for (int i = 1; i <= 11; i++) {
                threadPoolExecutor.execute(()->{
                    System.out.println(Thread.currentThread().getName()+" ==> Run ok .");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPoolExecutor.shutdown();//使用完关闭池
        }
    }

}
